// app/routes/templates.js
var express    = require('express'),  
    Template   = require('../models/Template');

module.exports = (function ()  
{
    var router = express.Router();

    router.post('/', function (req, res)
    {
        var templateName = req.body.template, // Retrieve the name of the template directory we are going to scan
            fs           = require('fs'); // Require Nodes file system module

        Template.find({name : templateName}, function (err, template) // Find the template based on the templates name
        {
            if (template.length) // If the template already exists return early and send back message 
            {
                res.json({error : 'Template exists'});
            }

            var newTemplate = new Template(); // Create a new instance of our Template schema

            newTemplate.name    = templateName; // Set the templates name
            newTemplate.modules = []; // Initialise an array that will hold the html modules

            fs.readdir('app/templates/' + templateName + '/modules', function (err, files) // Read the templates directory, our files will be available in the files parameter.
            {
                if (err) // If an error occured return it
                {
                    res.json(err);
                }

                files.forEach(function (file, index) // Each file in the templates directory
                {   
                    var fileName = file.split('.')[0],
                        fileName = fileName.replace('_', ' '); // Create a nice name for our module from the filename

                    newTemplate.modules.push( // Push a new object into the templates modules array
                    {
                        name : fileName, // Set it's name to our created filename
                        html : fs.readFileSync('app/templates/'+ templateName +'/modules/' + file, 'utf-8') // Set the html to the contents of the file parsed in utf-8 encoding.
                    });
                });

                newTemplate.save(function (err) // Save the template and respond accordingly
                {
                    if (err)
                    {
                        res.json(err);
                    }

                    res.json({success : true});
                });                 
            })
        } 
    });
}());